import cv2
import subprocess
import numpy as np

def start_scrcpy():
    """启动 scrcpy 并返回视频流"""
    # 指定 scrcpy 的完整路径
    scrcpy_path = r"C:\Users\lagen\Desktop\scrcpy-win64-v3.1\scrcpy.exe"  # 根据实际路径修改
    command = [scrcpy_path, "--no-display", "--max-fps=30", "--video-encoder=raw"]
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    # 使用 OpenCV 捕获视频流
    video_capture = cv2.VideoCapture("pipe:0", cv2.CAP_FFMPEG)
    if not video_capture.isOpened():
        print("无法打开视频流，请检查 scrcpy 是否安装并运行。")
        return None

    return video_capture

def get_phone_resolution():
    """获取手机屏幕分辨率"""
    try:
        result = subprocess.run(["adb", "shell", "wm", "size"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
        if result.returncode != 0:
            print("获取手机分辨率失败，请确保设备已连接。")
            return None
        # 解析分辨率
        match = re.search(r"(\d+)x(\d+)", result.stdout)
        if match:
            width = int(match.group(1))
            height = int(match.group(2))
            return width, height
        else:
            print("无法解析手机分辨率。")
            return None
    except Exception as e:
        print(f"获取手机分辨率时出错：{e}")
        return None

def main():
    """主逻辑：实时处理视频流"""
    # 启动 scrcpy 并获取视频流
    video_capture = start_scrcpy()
    if video_capture is None:
        return

    # 获取手机分辨率
    resolution = get_phone_resolution()
    if resolution is None:
        return

    phone_width, phone_height = resolution
    print(f"手机分辨率：{phone_width}x{phone_height}")

    try:
        # 创建 OpenCV 窗口
        cv2.namedWindow("Phone Screen", cv2.WINDOW_NORMAL)

        while True:
            # 读取视频帧
            ret, frame = video_capture.read()
            if not ret:
                print("无法读取视频帧，退出程序。")
                break

            # 调整窗口大小，按手机分辨率比例显示
            frame_height, frame_width = frame.shape[:2]
            scale = min(1.0, 800 / max(frame_width, frame_height))  # 限制窗口最大大小为 800x800
            window_width = int(frame_width * scale)
            window_height = int(frame_height * scale)
            cv2.resizeWindow("Phone Screen", window_width, window_height)

            # 显示视频帧
            cv2.imshow("Phone Screen", frame)

            # 按 'q' 键退出
            if cv2.waitKey(1) & 0xFF == ord('q'):
                print("程序已停止。")
                break
    except Exception as e:
        print(f"程序运行出错：{e}")
    finally:
        # 释放资源
        video_capture.release()
        cv2.destroyAllWindows()

if __name__ == "__main__":
    main()